package car.manager;

import java.util.LinkedList;

import business_layer.UserProfileManager;
import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class BackStageManager extends Application {

	private UserProfileManager userProfileManager;
	private DataBaseConnection dbc;

	//this is not cool
	private enum profile_indexes {
		ID, NAME, CREDIT, EXPERIENCE
	}

	public void onCreate() {
		super.onCreate();

		dbc = new DataBaseConnection(this);

		createManagers();

		loadProfiles();
	}

	private void createManagers() {
		//Instantiate all managers
		userProfileManager = new UserProfileManager(this);	
	}

	private void loadProfiles() {

		LinkedList<UserProfile> upList = new LinkedList<UserProfile>();

		//should this be on DatabaseConnection?
		SQLiteDatabase database = dbc.getReadableDatabase();
		Cursor cursor = database.query(DataBaseConnection.PROFILE_TABLE, null,
				null, null, null, null, null, null);

		//if Profile table is not empty
		if (cursor.moveToFirst()) {
			do {
				upList.add(
						new UserProfile(cursor.getInt(profile_indexes.ID.ordinal()),
								cursor.getString(profile_indexes.NAME.ordinal()),
								cursor.getFloat(profile_indexes.CREDIT.ordinal()),
								cursor.getInt(profile_indexes.EXPERIENCE.ordinal()))
						);

			} while (cursor.moveToNext());

			if(upList!=null && !upList.isEmpty()){
				userProfileManager.setUserProfileList(upList);
			}

		}
		database.close();


	}



	//if you ad an object without an id, does the database deal with it ?
	//pre-condition must be verified:
	//UserProfile up can't be null
	//all others values shouldn't be null neither
	public boolean addProfile(UserProfile up) {

		SQLiteDatabase database = dbc.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(DataBaseConnection.PROFILE_ID, up.getId());
		values.put(DataBaseConnection.PROFILE_NAME, up.getName());
		values.put(DataBaseConnection.PROFILE_CREDIT, up.getMoney());
		values.put(DataBaseConnection.PROFILE_EXPERIENCE, up.getExperience());

		return database.insert(DataBaseConnection.PROFILE_TABLE, null, values) != 1 ? true
				: false;


	}

	public UserProfileManager getUserProfileManager() {

		return userProfileManager;
	}
}























